//index.js

let util = require("../../utils/util.js");
var baseImgUrl = util.baseImgUrl;
const app = getApp();


let openid;
let nav_id = 2;//当前nav的id
let last_id;//上次数据的最后一条数据的id
let newslist0 = [];
let city;//当前城市
let district;//当前区域
let moren_city = "徐州";
let zhiding;
let qita;
let activeId;//nav中选中的分类的id
//let visitedId = 0;//新闻列表中选中的新闻的id
var animation = wx.createAnimation({
  transformOrigin: "50% 50%",
  duration: 1000,
  timingFunction: "ease",
  delay: 0
})
module.exports = {
  animation: animation
}
Page({
  data: {
    networkStatus: true,
    networkStatus2: true,
    loadingStatus: true,//默认加载完成，true--正在加载中
    none_network: util.imgUrl + "none_network.png",
    loadgif: util.imgUrl + "loading.gif",//加载gif图
    loading: util.imgUrl + "loading.png",

    currentpage:1,//当前页数
    curpage:2,
    baseImgUrl: baseImgUrl,
    notNone: true,//是否为空 默认非空
    userInfo: "",
    hasUserInfo: "",
    city: "徐州",
    // visitedflag: false,//是否已读
    visitedarr: [],//保存已读新闻的id
    refreshnum: "10",//每次刷新更新数据条数
    refreshFlag: true,//是否显示刷新bar
    greyFlat: false,//是否显示城市提示框
    // optionsflag:false,//是否显示选择频道容器 true--显示  false--不显示
    classid: "",
    //模拟数据 nav
    navlist: [{
      id: 0,
      name: "关注",
    },
    {
      id: 1,
      name: "推荐",
    }
    ],
    topnews: [],
    newslists: [],
   
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    loading2: false,//新闻列表加载页面
    toView: "",
    activeId: "t",//选中的选项序号
    scrollLeft: 0,
  },
  //点击nav
  choseNav: function (e) {
    
    var that = this;
    var act_id = e.currentTarget.dataset.index;
    var this_index = e.currentTarget.dataset.index;
    var this_id = e.currentTarget.dataset.id;
    var is_city = e.currentTarget.dataset.iscity;
    that.data.classid = e.currentTarget.dataset.id;

    nav_id = this_id;
    var guanzhu_index = 0;//关注
    if (app.globalData.userInfo) {
      console.log("app.globalData.userInfo");
      console.log(app.globalData.userInfo);
      that.setData({
        notNone: true
      })
    } else {
      console.log("未授权");
      //点击关注按钮
      if (this_index == guanzhu_index) {
        that.setData({
          notNone: false
        })
      } else {
        //点击其他按钮
        that.setData({
          notNone: true
        })
      }
    }

    that.setData({
      //activeId: act_id,
      activeId: this_id,
      loading2: true,
    })
    app.globalData.navId2 = this_id;
    app.globalData.nav_index2 = this_index;

    //调用接口，请求数据
    //请求接口，获取新闻列表
    wx.request({
      url: util.shitang_newslist,
      data: {
        openid: app.globalData.openid,
        classid: this_id,
        is_city: is_city,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
        console.log(res);

        newslist0 = [];
        if (res.data.count != 0) {
          var newslists = res.data.content;
          var topnews = res.data.zhiding;
          that.setData({
            newslists: newslists,
            loading2: false,
            topnews: topnews,
          })
          for (var i = 0; i < newslists.Length; i++) {
            newslist0.push(newslists[i]);
          }

        }
      },
      fail: function (err) {
        console.log("err" + err);
        that.setData({
         
          loading2: false
        })
      }
    })

    var query = wx.createSelectorQuery();//创建节点查询器
    query.select('#nav' + this_index).boundingClientRect();//选择id='#item-' + selectedId的节点，获取节点位置信息的查询请求
    query.select('#scroll-view').boundingClientRect();//获取滑块的位置信息
    //获取滚动位置
    query.select('#scroll-view').scrollOffset();//获取页面滑动位置的查询请求
    query.exec(function (res) {
      // console.log("res:",res)
      that.setData({
        scrollLeft: res[2].scrollLeft + res[0].left + res[0].width / 2 - res[1].width / 2
      });
    });




  },


  onLoad: function () {
    console.log("---------------shitang onload-----------------");
    var page = this;
    page.setData({
      loadingStatus: true
    })

    /*********判断网络状态***************** */
    wx.getNetworkType({
      success: function (res) {
        var networkType = res.networkType;
        if (networkType == "none" || networkType == "unknown") {
          page.setData({
            networkStatus: false
          })
        } else {
          page.setData({
            networkStatus: true,

          })
        }
      }, fail: function (err) {
        console.log("获取网络失败" + err);
        page.setData({
          networkStatus: false
        })
      }
    })

    if (app.globalData.userInfo) {
      console.log("----------已授权----------------")
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        notNone: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        page.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          page.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }


    //访问接口,获取nav
    wx.request({

      url: util.shitangNav,
      data: {
        openid: app.globalData.openid
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
        console.log("----- success-------");
        console.log(res);
        if (res) {
          //有返回值
          var navlist = res.data.daohang;
          activeId = res.data.daohang[1].id;
          page.data.classid = res.data.daohang[1].id;
          page.setData({
            navlist: res.data.daohang,  //上部导航
            topnews: res.data.zhiding,  //置顶数据
            newslists: res.data.tuijian, //推荐数据
            loadingStatus: false
          })
        } else {
          console.log("返回nav为空，导航栏为测试数据");

        }

      },
      fail: function (err) {
        console.log("getNav接口调用失败");
        page.setData({
          loadingStatus: true
        })
      }
    })

    app.globalData.navId = "t";//初始化navId为推荐的id

    setTimeout(function () {

      page.setData({
        refreshFlag: false
      })
    }, 2500)
    /*******************定位***************/
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        //45f2637ce0ee391b9f552e20f1816e05
        page.loadCity(longitude, latitude)
      }
    })
  },

  
  loadCity: function (longitude, latitude) {
    var page = this
    wx.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo?key=45f2637ce0ee391b9f552e20f1816e05&location=' + longitude + ',' + latitude,
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        // success  
        city = res.data.regeocode.addressComponent.city;
        city = city.split("市")[0];//截取城市名

        district = res.data.regeocode.addressComponent.district;
        console.log("----------"+city+"****************"+district+"*********************");

        page.setData({
          city: city
        })
        if (city != moren_city) {
          page.setData({
            greyFlag: true
          })
        }
      },
      fail: function () {
        page.setData({ currentCity: "获取定位失败" });
      },

    })
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  /*************下拉刷新**************/
  onPullDownRefresh: function () {
    var that = this;

    wx.showNavigationBarLoading(); //在标题栏中显示加载图标
    that.setData({
      refreshFlag: true
    })
    wx.stopPullDownRefresh();

    setTimeout(function () {
      wx.hideNavigationBarLoading()
      that.setData({
        refreshFlag: false
      })
    }, 3000)
    that.data.currentpage = that.data.currentpage+1;
    wx.request({
      url: util.down_load,
      data: {
        classid: that.data.classid,
        openid: app.globalData.openid,
        page: that.data.currentpage,
        zhanshi: 'shitang',
        is_city:0,
      },
      success: function (res) {
        that.setData({
          networkStatus: true,
          networkStatus2: true
        })
        that.data.refreshnum = res.data.refreshnum

        if (res.data.refreshnum > 0) {
          var content = res.data.content;
          content = content.concat(that.data.newslists);

          that.setData({
            newslists: content,
            refreshnum: res.data.refreshnum
          })


        } else {

          that.setData({
            refreshnum: 0
          })
        }
        that.data.currentpage++;

      }, fail: function (err) {
        console.log(err);
        that.setData({
          networkStatus2: false
        })
      }
    })
 },

  /*******上拉加载************ */
  onReachBottom: function () {
    console.log("***********到达底部***************")
    var that = this;
    var curpage=  that.data.curpage;
    that.data.curpage = that.data.curpage + 1;
    //请求后台，获取数据
    wx.request({
      url: util.up_load,
      data: {
        classid: that.data.classid,
        openid: app.globalData.openid,
        page: that.data.curpage,
        zhanshi:'shitang',
        is_city:0,
      },
      success: function (res) {
        console.log("获取数据...");
        console.log(res);
        curpage++;
        wx.showLoading({
          title: '正在加载中...',
        })
        setTimeout(function () {
          wx.hideLoading()

        }, 1000)
        if (res.data.content.length > 0) {
          var content = res.data.content;
          var newslists = that.data.newslists.concat(content);


          that.setData({
            newslists: newslists
          })
        } else {
          setTimeout(function () {
            wx.showToast({
              title: '没有更多数据加载',
              icon: "none"
            })
          }, 1000)
        }
      },
      fail: function () {
        console.log("没有获取数据");
        wx.showLoading({
          title: '网络无法链接',
        })
        setTimeout(function () {
          wx.hideLoading()

        }, 1000)
      }
    })
 },

  //关闭城市提示框
  shut: function () {
    var that = this;
    that.setData({
      greyFlag: false,
      city: moren_city
    })
    //请求后台，获取徐州的数据，将城市改为徐州
  },

  //选择城市
  chosecity: function () {
    var that = this;
   
    wx.navigateTo({
      url: '/pages/location/location',
    })

  },

  //申请加盟
  joinIn: function () {
    //跳页
  },

  //进入选择页面
  getmore: function () {
    
    wx.navigateTo({
      url: '/pages/options2/options2?reason=shitang',
    })

  },
  //跳转至新闻页面
  newsdetail: function (e) {

    var that = this;
    var thisid = e.currentTarget.dataset.id;
    that.data.visitedarr.push(thisid);
    
    wx.navigateTo({
      url: '/pages/detail/detail?newid=' + thisid,
    })
  },
  //跳转至视频页面
  audiodetail: function (e) {

    var that = this;
    var thisid = e.currentTarget.dataset.id;
    that.data.visitedarr.push(thisid);
    wx.navigateTo({
      url: '/pages/audio/audio?newid=' + thisid,
    })
  },
  //跳转至搜索页
  search: function () {
    wx.navigateTo({
      url: '/pages/search/search',
      success: function (res) {

      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  //onshow
  onShow: function () {
    
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        //45f2637ce0ee391b9f552e20f1816e05
        that.loadCity(longitude, latitude)
      }, fail: function () {
        console.log("----------用户拒绝定位-------------");
      }
    })

    if (app.globalData.areaid == '') {
      var areaid = '';
    } else {
      var areaid = app.globalData.areaid;
    }
    var navId2;
    if (app.globalData.navId2 == '') {
       navId2 = 't';
    } else {
       navId2 = app.globalData.navId2;
    }

    // //访问接口,获取nav
    wx.request({

      url: util.st_get_daohang,
      data: {
        openid: app.globalData.openid
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
        console.log("-----获取nav success-------");
        console.log(res);
        if (res) {
          //有返回值
          var navlist = res.data.daohang;
          activeId = navId2;
          //that.data.classid = res.data.daohang[1].id;
          that.setData({
            navlist: res.data.daohang,  //上部导航
           })

          var query = wx.createSelectorQuery();//创建节点查询器
          query.select('#nav' + app.globalData.nav_index).boundingClientRect();//选择id='#item-' + selectedId的节点，获取节点位置信息的查询请求
          query.select('#scroll-view').boundingClientRect();//获取滑块的位置信息
          //获取滚动位置
          query.select('#scroll-view').scrollOffset();//获取页面滑动位置的查询请求
          query.exec(function (res) {
            // console.log("res:",res)
            that.setData({
              scrollLeft: res[2].scrollLeft + res[0].left + res[0].width / 2 - res[1].width / 2,
              
            });
          });
          
        } else {
          console.log("返回nav为空，导航栏为测试数据")
        }

        that.setData({
          activeId: navId2,
          toView: app.globalData.nav_index2
        })
        
        wx.request({
          url: util.shoueyNav,
          data: {
            openid: app.globalData.openid,
            areaid: areaid,
          },
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded" //post
          },
          success: function (res) {
            that.setData({
              networkStatus: true,
              loadingStatus: false
            })

            if (res) {
              console.log("------------index---------------");
              console.log(res);
              //有返回值
              var navlist = res.data.daohang;
              that.setData({

                topnews: res.data.zhiding,  //置顶数据
                newslists: res.data.tuijian, //推荐数据
              })
            } else {
            }

            //请求接口，获取置顶和新闻列表
            wx.request({
              url: util.shitangNav,
              data: {
                openid: app.globalData.openid,
                areaid: areaid,
              },
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded" //post
              },
              success: function (res) {
                that.setData({
                  networkStatus: true,
                  loadingStatus: false
                })

                if (res) {
                  console.log("------------shitang onshow---------------");
                  console.log(res);
                  //有返回值
                 
                  that.setData({
                    topnews: res.data.zhiding,  //置顶数据
                    newslists: res.data.tuijian, //推荐数据
                  })
                } else {

                }

              },
              fail: function (err) {
                page.setData({
                  loadingStatus: true
                })
              }
            })

          },
          fail: function (err) {
            page.setData({
              loadingStatus: true
            })
          }
        })

      },
      fail: function (err) {
        console.log("getNav接口调用失败");
      }
    })
    

   
    var newsLen = that.data.newslists.length;
    var visitLen = that.data.visitedarr.length;
   
    for (var i = 0; i < newsLen; i++) {
      for (var j = 0; j < visitLen; j++) {
        if (that.data.newslists[i].id == that.data.visitedarr[j]) {
          that.data.newslists[i].visited = true;
          
          that.setData({
            newslists: that.data.newslists
          })
        }
      };
    }
   
  },
  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function () {

  }
 

})

//下拉刷新图标旋转动画
function updateRefreshIcon() {
  var deg = 0;
  var that = this;
  console.log('旋转开始了.....')
  //创建动画
  var animation = wx.createAnimation({
    duration: 1500
  })
  var timer = setInterval(function () {
    if (!that.data.refreshing)
      clearInterval(timer)
    animation.rotateZ(deg).step();//在Z轴旋转一个deg角度
    deg += 360
    that.setData({
      refreshAnimation: animation.export()
    })
  }, 500);
}
